<template>
  <div class="food-manage">
    <div class="page-header">
      <h1>美食管理</h1>
      <div class="header-actions">
        <button @click="currentTab = 'foods'" :class="{ active: currentTab === 'foods' }" class="tab-btn">
          美食列表
        </button>
        <button @click="currentTab = 'restaurants'" :class="{ active: currentTab === 'restaurants' }" class="tab-btn">
          餐厅列表
        </button>
        <button @click="showAddDialog = true" class="add-btn">
          <span class="btn-icon">➕</span>
          添加{{ currentTab === 'foods' ? '美食' : '餐厅' }}
        </button>
      </div>
    </div>

    <!-- 美食管理 -->
    <div v-if="currentTab === 'foods'" class="foods-section">
      <div class="search-bar">
        <input 
          v-model="searchKeyword" 
          @input="searchFoods"
          placeholder="搜索美食名称..." 
          class="search-input"
        >
      </div>

      <div class="data-table">
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>美食名称</th>
              <th>描述</th>
              <th>价格</th>
              <th>分类</th>
              <th>特色</th>
              <th>评分</th>
              <th>标签</th>
              <th>图片</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="food in filteredFoods" :key="food.id">
              <td>{{ food.id }}</td>
              <td class="name-cell">{{ food.name }}</td>
              <td class="desc-cell">{{ food.description.substring(0, 40) }}...</td>
              <td class="price-cell">¥{{ food.price }}</td>
              <td>{{ food.category }}</td>
              <td class="feature-cell">{{ food.specialFeature }}</td>
              <td>{{ food.rating }}</td>
              <td>{{ food.tags }}</td>
              <td class="image-cell">
                <img v-if="food.imageUrl" :src="'http://localhost:8080/' + food.imageUrl" :alt="food.name" class="thumbnail">
                <span v-else class="no-image">无图片</span>
              </td>
              <td class="actions-cell">
                <button @click="editFood(food)" class="edit-btn">编辑</button>
                <button @click="deleteFood(food.id)" class="delete-btn">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 餐厅管理 -->
    <div v-if="currentTab === 'restaurants'" class="restaurants-section">
      <div class="search-bar">
        <input 
          v-model="searchKeyword" 
          @input="searchRestaurants"
          placeholder="搜索餐厅名称..." 
          class="search-input"
        >
      </div>

      <div class="data-table">
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>餐厅名称</th>
              <th>地址</th>
              <th>描述</th>
              <th>人均价格</th>
              <th>营业时间</th>
              <th>电话</th>
              <th>评分</th>
              <th>特色菜</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="restaurant in filteredRestaurants" :key="restaurant.id">
              <td>{{ restaurant.id }}</td>
              <td class="name-cell">{{ restaurant.name }}</td>
              <td class="address-cell">{{ restaurant.address }}</td>
              <td class="desc-cell">{{ restaurant.description ? restaurant.description.substring(0, 20) + '...' : '' }}</td>
              <td>{{ restaurant.averagePrice }}</td>
              <td>{{ restaurant.openingHours }}</td>
              <td class="phone-cell">{{ restaurant.phone }}</td>
              <td class="rating-cell">
                <span class="rating">⭐ {{ restaurant.rating }}</span>
              </td>
              <td class="specialty-cell">{{ restaurant.specialtyDish }}</td>
              <td class="actions-cell">
                <button @click="editRestaurant(restaurant)" class="edit-btn">编辑</button>
                <button @click="deleteRestaurant(restaurant.id)" class="delete-btn">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <div v-if="showAddDialog || showEditDialog" class="dialog-overlay" @click="closeDialog">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h2>{{ getDialogTitle() }}</h2>
          <button @click="closeDialog" class="close-btn">✕</button>
        </div>
        <div class="dialog-body">
          <!-- 美食表单 -->
          <form v-if="currentTab === 'foods'" @submit.prevent="saveFood">
            <div class="form-group">
              <label>美食名称：</label>
              <input v-model="currentFood.name" type="text" required>
            </div>
            <div class="form-group">
              <label>描述：</label>
              <textarea v-model="currentFood.description" rows="3" required></textarea>
            </div>
            <div class="form-group">
              <label>价格：</label>
              <input v-model.number="currentFood.price" type="number" min="0" step="0.01" required>
            </div>
            <div class="form-group">
              <label>分类：</label>
              <input v-model="currentFood.category" type="text">
            </div>
            <div class="form-group">
              <label>特色：</label>
              <input v-model="currentFood.specialFeature" type="text" required>
            </div>
            <div class="form-group">
              <label>评分：</label>
              <input v-model.number="currentFood.rating" type="number" min="0" max="5" step="0.1">
            </div>
            <div class="form-group">
              <label>标签 (逗号分隔)：</label>
              <input v-model="currentFood.tags" type="text">
            </div>
            <div class="form-group">
              <label>美食图片：</label>
              <ImageSelector v-model="currentFood.imageUrl" placeholder="选择美食图片" />
            </div>
            <div class="form-actions">
              <button type="button" @click="closeDialog" class="cancel-btn">取消</button>
              <button type="submit" class="save-btn">保存</button>
            </div>
          </form>

          <!-- 餐厅表单 -->
          <form v-if="currentTab === 'restaurants'" @submit.prevent="saveRestaurant">
            <div class="form-group">
              <label>餐厅名称：</label>
              <input v-model="currentRestaurant.name" type="text" required>
            </div>
            <div class="form-group">
              <label>地址：</label>
              <input v-model="currentRestaurant.address" type="text" required>
            </div>
            <div class="form-group">
              <label>描述：</label>
              <textarea v-model="currentRestaurant.description" rows="3"></textarea>
            </div>
            <div class="form-group">
              <label>人均价格：</label>
              <input v-model="currentRestaurant.averagePrice" type="text">
            </div>
            <div class="form-group">
              <label>营业时间：</label>
              <input v-model="currentRestaurant.openingHours" type="text">
            </div>
            <div class="form-group">
              <label>电话：</label>
              <input v-model="currentRestaurant.phone" type="tel" required>
            </div>
            <div class="form-group">
              <label>评分：</label>
              <input v-model.number="currentRestaurant.rating" type="number" min="0" max="5" step="0.1" required>
            </div>
            <div class="form-group">
              <label>特色菜：</label>
              <input v-model="currentRestaurant.specialtyDish" type="text" required>
            </div>
            <div class="form-actions">
              <button type="button" @click="closeDialog" class="cancel-btn">取消</button>
              <button type="submit" class="save-btn">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import ImageSelector from '@/components/ImageSelector.vue'

interface Food {
  id?: number
  name: string
  description: string
  price: number
  specialFeature: string
  imageUrl: string
  rating: number
  tags: string
  category: string
}

interface Restaurant {
  id?: number
  name: string
  address: string
  phone: string
  rating: number
  specialtyDish: string
  description: string
  averagePrice: string
  openingHours: string
}

const currentTab = ref('foods')
const searchKeyword = ref('')
const showAddDialog = ref(false)
const showEditDialog = ref(false)

const foods = ref<Food[]>([])
const filteredFoods = ref<Food[]>([])
const currentFood = ref<Food>({
  name: '',
  description: '',
  price: 0,
  specialFeature: '',
  imageUrl: '',
  rating: 0,
  tags: '',
  category: ''
})

const restaurants = ref<Restaurant[]>([])
const filteredRestaurants = ref<Restaurant[]>([])
const currentRestaurant = ref<Restaurant>({
  name: '',
  address: '',
  phone: '',
  rating: 0,
  specialtyDish: '',
  description: '',
  averagePrice: '',
  openingHours: ''
})

const loadFoods = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/foods')
    if (response.ok) {
      foods.value = await response.json()
      filteredFoods.value = foods.value
    }
  } catch (error) {
    console.error('加载美食数据失败:', error)
  }
}

const loadRestaurants = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/restaurants')
    if (response.ok) {
      restaurants.value = await response.json()
      filteredRestaurants.value = restaurants.value
    }
  } catch (error) {
    console.error('加载餐厅数据失败:', error)
  }
}

const searchFoods = () => {
  if (!searchKeyword.value.trim()) {
    filteredFoods.value = foods.value
  } else {
    filteredFoods.value = foods.value.filter(food =>
      food.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
}

const searchRestaurants = () => {
  if (!searchKeyword.value.trim()) {
    filteredRestaurants.value = restaurants.value
  } else {
    filteredRestaurants.value = restaurants.value.filter(restaurant =>
      restaurant.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
}

const editFood = (food: Food) => {
  currentFood.value = { ...food }
  showEditDialog.value = true
}

const editRestaurant = (restaurant: Restaurant) => {
  currentRestaurant.value = { ...restaurant }
  showEditDialog.value = true
}

const deleteFood = async (id: number | undefined) => {
  if (id === undefined) return;
  if (!confirm('确定要删除这个美食吗？')) return;
  try {
    const response = await fetch(`http://localhost:8080/api/foods/${id}`, {
      method: 'DELETE'
    });
    if (response.ok) {
      alert('删除成功');
      loadFoods();
    } else {
      alert('删除失败');
    }
  } catch (error) {
    alert('删除美食失败');
  }
};

const deleteRestaurant = async (id: number | undefined) => {
  if (id === undefined) return;
  if (!confirm('确定要删除这个餐厅吗？')) return;
  try {
    const response = await fetch(`http://localhost:8080/api/restaurants/${id}`, {
      method: 'DELETE'
    });
    if (response.ok) {
      alert('删除成功');
      loadRestaurants();
    } else {
      alert('删除失败');
    }
  } catch (error) {
    alert('删除餐厅失败');
  }
};

const saveFood = async () => {
  try {
    const url = showAddDialog.value 
      ? 'http://localhost:8080/api/foods'
      : `http://localhost:8080/api/foods/${currentFood.value.id}`
    
    const method = showAddDialog.value ? 'POST' : 'PUT'
    
    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(currentFood.value)
    })
    
    if (response.ok) {
      alert(showAddDialog.value ? '添加成功' : '更新成功')
      closeDialog()
      loadFoods()
    } else {
      alert(showAddDialog.value ? '添加失败' : '更新失败')
    }
  } catch (error) {
    console.error('保存美食失败:', error)
    alert('保存美食失败')
  }
}

const saveRestaurant = async () => {
  try {
    const url = showAddDialog.value 
      ? 'http://localhost:8080/api/restaurants'
      : `http://localhost:8080/api/restaurants/${currentRestaurant.value.id}`
    
    const method = showAddDialog.value ? 'POST' : 'PUT'
    
    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(currentRestaurant.value)
    })
    
    if (response.ok) {
      alert(showAddDialog.value ? '添加成功' : '更新成功')
      closeDialog()
      loadRestaurants()
    } else {
      alert(showAddDialog.value ? '添加失败' : '更新失败')
    }
  } catch (error) {
    console.error('保存餐厅失败:', error)
    alert('保存餐厅失败')
  }
}

const getDialogTitle = () => {
  if (showAddDialog.value) {
    return `添加${currentTab.value === 'foods' ? '美食' : '餐厅'}`
  }
  if (showEditDialog.value) {
    return `编辑${currentTab.value === 'foods' ? '美食' : '餐厅'}`
  }
  return ''
}

const closeDialog = () => {
  showAddDialog.value = false
  showEditDialog.value = false
  currentFood.value = {
    name: '',
    description: '',
    price: 0,
    specialFeature: '',
    imageUrl: '',
    rating: 0,
    tags: '',
    category: ''
  }
  currentRestaurant.value = {
    name: '',
    address: '',
    phone: '',
    rating: 0,
    specialtyDish: '',
    description: '',
    averagePrice: '',
    openingHours: ''
  }
}

onMounted(() => {
  loadFoods()
  loadRestaurants()
})
</script>

<style scoped>
.food-manage {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header h1 {
  color: #2c3e50;
  margin: 0;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.tab-btn {
  padding: 8px 16px;
  border: 2px solid #3498db;
  background: white;
  color: #3498db;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.tab-btn.active {
  background: #3498db;
  color: white;
}

.add-btn {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  background: #27ae60;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s;
}

.add-btn:hover {
  background: #229954;
}

.btn-icon {
  margin-right: 8px;
}

.search-bar {
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.data-table {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.name-cell {
  font-weight: 500;
  color: #2c3e50;
}

.desc-cell, .address-cell, .specialty-cell {
  color: #666;
  max-width: 150px;
}

.price-cell {
  font-weight: 600;
  color: #e74c3c;
}

.rating-cell .rating {
  background: #f39c12;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.image-cell .thumbnail {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
}

.no-image {
  color: #999;
  font-style: italic;
}

.actions-cell {
  white-space: nowrap;
}

.edit-btn, .delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  margin-right: 8px;
}

.edit-btn {
  background: #3498db;
  color: white;
}

.edit-btn:hover {
  background: #2980b9;
}

.delete-btn {
  background: #e74c3c;
  color: white;
}

.delete-btn:hover {
  background: #c0392b;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 10px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.dialog-header h2 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #666;
}

.dialog-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #2c3e50;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
}

.cancel-btn, .save-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
}

.cancel-btn {
  background: #95a5a6;
  color: white;
}

.cancel-btn:hover {
  background: #7f8c8d;
}

.save-btn {
  background: #27ae60;
  color: white;
}

.save-btn:hover {
  background: #229954;
}
</style> 